package org.wyn.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieTool {
	private static final int age = -1;

	public static void setCookie(String key, String value, int age, HttpServletRequest request, HttpServletResponse response){
		String path = "/"; //request.getContextPath();
		Cookie cookie = new Cookie(key, value);
		cookie.setPath(path);
		cookie.setMaxAge(age);
		response.addCookie(cookie);
	}
	
	public static void setCookie(String key, String value, HttpServletRequest request, HttpServletResponse response){
		setCookie(key, value, age, request, response);
	}
	
	public static void deleteCookie(String key, HttpServletRequest request, HttpServletResponse response){
		String path = "/"; //request.getContextPath();
		Cookie cookie = new Cookie(key, "");
		cookie.setPath(path);
		cookie.setMaxAge(0);
		response.addCookie(cookie);
	}
	
	public static String getCookie(String key, HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		for (int i = 0; i < cookies.length; i++) {
			Cookie cookie = cookies[i];
			if(cookie.getName().equals(key)){
				return cookie.getValue();
			}
		}
		return null;
	}
	
	public static void setCookieSecurity(String key, String value, int age, HttpServletRequest request, HttpServletResponse response){
		value = CodeMD5.MD5_Code(value);
		value = BBSUtil.packString(value);
		setCookie(key, value, age, request, response);
	}
	public static String getCookieSecurity(String key, HttpServletRequest request) {
		String value = getCookie(key, request);
		return BBSUtil.unPackString(value);
	}
}
